
<template>
  <div class="course-detail">
    <Header />

    {{coursesData}}
    <!-- 课程主体内容 -->
    <div class="course-container" v-if="coursesData">
      <!-- 课程基本信息 -->
      <div class="course-info">
        <div class="course-image">
          <img :src="coursesData.course_img" :alt="coursesData.name">
        </div>
        <div class="course-summary">
          <h1 class="title">{{ coursesData.name }}</h1>
          <div class="stats">
            <span class="stat-item"><i class="fas fa-user"></i>{{ coursesData.students }}人在学</span>
            <span class="stat-item"><i class="fas fa-list"></i>{{coursesData.lessons}}课时</span>
            <span class="stat-item"><i class="fas fa-clock"></i>{{ coursesData.pub_lessons }}已发布课时</span>
          </div>
          <div class="price-info">
            <span class="current-price">{{ coursesData.price }}</span>
            <span class="original-price">{{ coursesData.original_price }}</span>
          </div>
          <button class="buy-btn" @click="handleCarts">加入购物车</button>
        </div>
      </div>

      <!-- 讲师信息 -->
      <div class="teacher-info">
        <div class="avatar">
          <img :src="coursesData.teacher.avatar" :alt="coursesData.teacher.name">
        </div>
        <div class="teacher-detail">
          <h3 class="name">{{coursesData.teacher.name}}</h3>
          <p class="title">{{ coursesData.teacher.title }}</p>
          <p class="description">{{ coursesData.teacher.signature }}</p>
        </div>
      </div>

      <!-- 课程大纲 -->
      <div class="course-outline">
        <h2 class="section-title">课程大纲</h2>
        <div class="outline-content">
          <!-- 第一章 章节和课时应该是循环出来的-->
          <div class="chapter" v-for="chapter in coursesData.chapters" :key="chapter.id">
            <div class="chapter-header">
              <h3>第{{chapter.number}}章:{{ chapter.title }}</h3>
              <span class="duration">共{{ chapter.lessons.length }}课时</span>
            </div>
            <div class="lessons">
              <div class="lesson" v-for="lesson in chapter.lessons" :key="lesson.id">
                <span class="lesson-title" v-if="lesson.is_free_trail === true"><a :href="lesson.link">{{ lesson.orders }}.{{lesson.title}}</a></span>
                <span class="lesson-title" v-else>{{ lesson.order }}:{{lesson.title}}</span>
                <span class="lesson-duration">{{ lesson.duration }}</span>
                <span class="free-tag" v-if="lesson.is_free_trail === true">免费</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 课程介绍 -->
      <div class="course-introduction">
        <h2 class="section-title">课程介绍</h2>
        <div class="introduction-content" v-html="coursesData.description">
        </div>
      </div>

      <!-- 课程收获 -->
      <div class="course-gains">
        <h2 class="section-title">课程收获</h2>
        <div class="gains-content" v-html="coursesData.outcomes">
        </div>
      </div>

      <!-- 适合人群 -->
      <div class="suitable-for">
        <h2 class="section-title">适合人群</h2>
        <div class="suitable-content" v-html="coursesData.audience">
        </div>
      </div>
    </div>
  </div>
</template>








<script lang="ts" setup>
import Header from '../components/Header.vue'
import {ref,reactive,onMounted} from "vue";
import axios from "axios";
import {useRoute} from "vue-router";
import {useRouter} from "vue-router";

const route = useRoute()
const id = route.params.id  //这个也是课程的id
const coursesData = ref(null)
const router = useRouter()

const fetchData = async () =>{
   const res = await axios.get(`http://localhost:8000/api/detail/${id}/`)
  if (res.data.code === 1){
    coursesData.value = res.data.data
    console.log('111111111获取课程详情成功')
    console.log(res.data)
  }
}


const handleCarts = async () => {
  // 还是要先拿到token才能进行干活
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token){
    alert('请先登录')
    router.push('/login')
    return
  }

  try{
    //如果登陆了就可以进行添加
    const res = await axios.post(`http://localhost:8000/api/add/`,{course_id:id,quantity:1},
        {headers: {"Authorization": `Bearer ${token}`}})

    if (res.status === 200){
      if (res.data.code === 1){
        alert('课程添加成功')
      }else if (res.data.code === 2){
        alert('请先登录')
        router.push('/login')
      }else if (res.data.code === 401){
        alert('登录已过期')
      }else {
        alert(res.data.message || '课程添加失败')
      }
    }else{
      alert('请求失败')
    }
  }catch (error){
    console.log(error)   //因为这里的catch是请求状态码部位200返回的，
    // 我们的401过期只在异常里处理的，但他返回的状态仍是401
    // 所以这里要进行处理

    if (error.response.status === 401){
      alert('登录已过期')
      const newToken = await refreshToken  //调用刷新过期token的方法

      if (newToken){  //如果有新的token就继续添加课程，还是需要换请求头
        const newAdd = await axios.post(`http://localhost:8000/api/add/`,{course_id:id,quantity:1},{
          headers:{
            'Authorization':`Bearer ${newToken}`
          }
        })

        if (newAdd.data.code === 1){
          alert('课程添加成功')
        }else{
          alert(newAdd.data.message || '课程添加失败')
        }
      }
    }else{
      alert('状态码为其他')
    }
  }

}


//刷新token的方法
const refreshToken = async () =>{
  //刷新token的接口，自动刷新
  const refresh_token = sessionStorage.getItem('refresh_token') || localStorage.getItem('refresh_token')
  if (!refresh_token){
    alert('没有token')
    return
  }

  const res = await axios.post(`http://localhost:8000/refresh/`, {refresh:refresh_token})
  //如果有返回了access说明刷新成功
  if (res.data.access){
    const newToken = res.data.access
    localStorage.setItem('token', newToken)
    sessionStorage.setItem('token', newToken)
    console.log('token刷新成功')
    return newToken
  }
}













onMounted(
    ()=>{
      fetchData()
    })
</script>

<style scoped>
.course-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.course-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 课程基本信息样式 */
.course-info {
  display: flex;
  gap: 30px;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.course-image {
  flex: 0 0 400px;
}

.course-image img {
  width: 100%;
  border-radius: 8px;
}

.course-summary {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 24px;
  color: #333;
  margin: 0 0 20px;
}

.stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  color: #666;
  font-size: 14px;
}

.stat-item i {
  margin-right: 5px;
}

.price-info {
  margin-bottom: 20px;
}

.current-price {
  font-size: 28px;
  color: #ff5858;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 16px;
}

.buy-btn {
  width: 180px;
  height: 48px;
  background: #ff5858;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.buy-btn:hover {
  background: #ff4040;
}

/* 讲师信息样式 */
.teacher-info {
  display: flex;
  gap: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.teacher-detail {
  flex: 1;
}

.teacher-detail .name {
  font-size: 18px;
  color: #333;
  margin: 0 0 5px;
}

.teacher-detail .title {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px;
}

.teacher-detail .description {
  color: #999;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

/* 课程大纲样式 */
.course-outline,
.course-introduction,
.course-gains,
.suitable-for {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  color: #333;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chapter {
  margin-bottom: 20px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.chapter-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.duration {
  color: #999;
  font-size: 14px;
}

.lessons {
  padding-left: 20px;
}

.lesson {
  display: flex;
  align-items: center;
  padding: 10px 0;
  color: #666;
  font-size: 14px;
}

.lesson-title {
  flex: 1;
}

.lesson-duration {
  color: #999;
  margin: 0 15px;
}

.free-tag {
  color: #52c41a;
  font-size: 12px;
  padding: 2px 6px;
  border: 1px solid #52c41a;
  border-radius: 4px;
}

/* 其他内容区域样式 */
.introduction-content,
.gains-content,
.suitable-content {
  color: #666;
  font-size: 14px;
  line-height: 1.8;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  margin-bottom: 10px;
}
</style>
